/*
 * @Date: 2023-03-04 16:34:32
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-18 09:10:17
 * @FilePath: \A19\backend\src\api\SourceManage\ApiUploadFile.ts
 */
import { ApiCall } from "tsrpc";
import { ReqUploadFile, ResUploadFile } from "../../shared/protocols/SourceManage/PtlUploadFile";
import upload from "../../utils/upload";
import { findFolder } from '../../utils/FindCurrentFolder';
import { Global } from '../../Global/index';
import { Folder } from "../../utils/Folder";
import { ObjectId } from "mongodb";

export default async function (call: ApiCall<ReqUploadFile, ResUploadFile>) {
    // TODO
    const root = await Global.collection('folders').findOne({
        course:call.req.course
    })
    if(!root) return call.error('课程不存在')

    const folder = findFolder(call.req.path,root)
    if(!folder) return call.error('文件夹不存在')

    try {
        // console.log(call.req.files);
        const promises = call.req.files.map(async file =>{
            const fileName = file.fileName
            const index= fileName.lastIndexOf('.')
            const type = fileName.slice(index + 1)
            const typeCate = file.fileType.slice(0,file.fileType.indexOf('/')) 
            // console.log(type);
            // console.log(typeCate);
            const path = await upload({
                folder:Folder.sources,
                type,
                typeCate,
                id:new ObjectId
            },file.fileData)
            console.log(path);
            folder.files.push({
                name:fileName,
                url:path
            })
         })
     
         await Promise.all(promises)

         await Global.collection('folders').updateOne({
            course:call.req.course
        },{
            $set:{
                folders:root.folders,
                files:root.files
            }
        })

         call.succ({
            files:folder.files,
            folders:folder.folders.map(f => f.name)
         })
    } catch (error) {
        if(error instanceof Error){
            console.log(error);
            return call.error(error.message)
        }
    }
}